#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, xmpp, os, time, smtplib
import socket

from email.MIMEText import MIMEText

running=1

#Данные нашего бота
botaccount = {
		'user': 'jabberbot', #без '@' и адреса сервера
		'password': '**********',
		'domain': 'jabberserver'
		}
		
#Данные gmail-аккаунта
gmailaccount = {
		'user': 'buzzuser', #без '@' и адреса сервера
		'password': '*********',
		'buzz': 'buzz@gmail.com',
		'server': '209.85.135.111', #smtp.gmail.com
		'port': 25
		}
		
##proxy = None
#proxy = {
		#'proxy': 'http://xxx.xxx.xxx.xxx:3128/',
		#'user': 'proxyuser',
		#'password': '*********'
		#}
		
#Список тех, кому можно писать в Buzz
white_list=['xxx@gmail.com',
			'xxx@jabber.ru'
			]



from threading import Thread

# Без постоянных запросов к серверу 
# xmpppy почему-то отваливается 
# через некоторое время бездействия.
class Ping(Thread):
	def __init__(self, connection):
		self.connection = connection
		Thread.__init__(self)
	def run(self):
		while running:
			time.sleep(60)
			self.connection.send("<iq type='get'> <ping xmlns='urn:xmpp:ping' /> </iq>")	
			
#Посылка сообщения в Google Buzz
def buzzsend(text):
	name = gmailaccount['user']
	pw = gmailaccount['password']
	to = gmailaccount['buzz']
	server=gmailaccount['server']
	port=gmailaccount['port']
	subj = text
	mesg = 'Should be ignored :('
	
	#формируем сообщение
	msg = MIMEText(mesg)
	msg['Subject'] = subj
	msg['From'] = name
	msg['To'] = to
	
	#if proxy != None:
		#os.environ['smtp_proxy'] = proxy['proxy']
		#os.environ['proxy-username'] = proxy['user']
		#os.environ['proxy-password'] = proxy['password'] 

	#соединяемся с почтовым сервером и отсылаем сообщение
	try:
		mail = smtplib.SMTP(server, port)
		mail.set_debuglevel(1) #отладка
		mail.starttls()
		mail.login(name, pw)
		mail.sendmail(name, to, msg.as_string())
		mail.quit()
		
	#
	#TEST IT!
	#
	except socket.error:
		return "Could not connect to SMTP server."
	except smtplib.SMTPConnectError:
		return "Error occurred during establishment of a connection with the server."
	except smtplib.SMTPAuthenticationError:
		return "SMTP authentication went wrong. Most probably the server didn’t accept the username/password combination provided."
	except smtplib.SMTPServerDisconnected:
		return "This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server."
	except smtplib.SMTPException:
		return "Oops! We have error!"

	return "Done."
			
# Обработка сообщений от бота
def messageHandler(connection, message):
 
	reply = ""
 
	text = message.getBody()
	user = message.getFrom()
	userStr = user.getStripped()
 
	# Отсеиваем статус-сообщения и другую ерунду.
	if userStr in white_list:
		if text:
			reply=buzzsend(text)
			connection.send(xmpp.Message(user,reply))
	else:
		connection.send(xmpp.Message(user,'Sorry, you do not have permissions for post to this Buzz.'))
		
# Для того, чтобы бот показывал он-лайн стутс.
def presenceHandler(connection, message):
	if message.getType() == 'subscribe':
		connection.send(xmpp.Presence(to=message.getFrom(), typ='subscribed'))
 
# Инициализация соединения с jabber-сервером 
connection = xmpp.Client(botaccount['domain'],debug=[])
connectionResource = connection.connect()
 
if not connectionResource:
	print "Unable to connect for jabber server"
	sys.exit(1)
 
authResource = connection.auth(botaccount['user'], botaccount['password'])
 
if not authResource:
	print "Incorrect bot login or password"
	sys.exit(1)
 
connection.RegisterHandler('message', messageHandler)
connection.RegisterHandler('presence', presenceHandler)
connection.sendInitPresence(0)
 
try:
	# Пинги.
	Ping(connection).start()
	while running:
		connection.Process(1)
except KeyboardInterrupt:
	sys.exit(1)
